package hqb.dev.webdeploy.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author HQB--2024-04-24
 **/
@Component
public class ValidateIntercept implements WebMvcConfigurer {

    @Value("${validate.enabled:false}")
    private boolean validateEnabled;
    @Value("${validate.token}")
    private String validateToken;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                if (validateEnabled) {
                    String token = request.getHeader("token");
                    if (token == null || !token.equals(validateToken)) {
                        response.sendError(401, "Unauthorized access denied");
                        return false;
                    }
                }
                return HandlerInterceptor.super.preHandle(request, response, handler);
            }
        }).addPathPatterns("/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
